// 通用文件预览：在 Electron 中会被主进程 setWindowOpenHandler 接管，
// 打开为主窗口的模态子窗口；在浏览器环境回退为新标签页。

export function openFilePreviewWindow(file) {
  if (!file) return;
  const objectUrl = URL.createObjectURL(file);
  const name = (file.name || '未命名').toLowerCase();
  const faviconUrl = window.location.origin + '/favicon.ico';

  const baseHead = (title) => `
    <title>${title}</title>
    <link rel="icon" href="${faviconUrl}" type="image/x-icon">
    <style>
      html, body { 
        margin: 0; 
        padding: 0; 
        height: 100%; 
        overflow: hidden; 
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif;
        background: #f8f9fa;
      }
      
      /* 自定义滚动条样式 - 与软件风格一致 */
      *::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }
      
      *::-webkit-scrollbar-track {
        background: #f1f3f4;
        border-radius: 4px;
      }
      
      *::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
        border-radius: 4px;
        transition: background 0.2s ease;
      }
      
      *::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(135deg, #4b5563 0%, #374151 100%);
      }
      
      *::-webkit-scrollbar-corner {
        background: #f1f3f4;
      }
      
      /* 通用按钮样式 */
      .preview-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 10px 20px;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        text-decoration: none;
        transition: all 0.2s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      }
      
      .preview-btn--primary {
        background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
        color: #ffffff;
      }
      
      .preview-btn--primary:hover {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        box-shadow: 0 4px 8px rgba(34, 197, 94, 0.3);
      }
      
      .preview-btn--secondary {
        background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
        color: #ffffff;
      }
      
      .preview-btn--secondary:hover {
        background: linear-gradient(135deg, #4b5563 0%, #374151 100%);
        box-shadow: 0 4px 8px rgba(107, 114, 128, 0.3);
      }
      
      /* 错误和提示页面样式 */
      .preview-error {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        padding: 40px;
        text-align: center;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      }
      
      .preview-error h2 {
        margin: 0 0 16px 0;
        font-size: 24px;
        font-weight: 600;
        color: #374151;
      }
      
      .preview-error p {
        margin: 0 0 24px 0;
        font-size: 16px;
        color: #6b7280;
        line-height: 1.5;
      }
      
      .preview-error .file-type {
        display: inline-block;
        padding: 4px 12px;
        background: #e5e7eb;
        border-radius: 12px;
        font-size: 12px;
        color: #6b7280;
        font-weight: 500;
      }
    </style>
  `;

  let content = '';

  if (name.endsWith('.pdf')) {
    content = `
      <!DOCTYPE html>
      <html>
      <head>
        ${baseHead(file.name)}
        <style>
          embed {
            width: 100vw; 
            height: 100vh; 
            border: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
          }
        </style>
      </head>
      <body>
        <embed src="${objectUrl}" type="application/pdf" />
      </body>
      </html>
    `;
  } else if (/\.(png|jpg|jpeg|gif|bmp|webp)$/i.test(name)) {
    content = `
      <!DOCTYPE html>
      <html>
      <head>
        ${baseHead(file.name)}
        <style>
          * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            border: none;
            outline: none;
          }
          html, body {
            margin: 0;
            padding: 0;
            background: #000;
            width: 100%;
            height: 100%;
            overflow: hidden;
          }
          .image-container {
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            margin: 0;
            padding: 0;
            border: none;
            outline: none;
          }
          img {
            cursor: pointer;
            transform-origin: center center;
            user-select: none;
            -webkit-user-drag: none;
            -moz-user-select: none;
            -ms-user-select: none;
            pointer-events: auto;
            display: block;
            object-fit: contain;
            margin: 0;
            padding: 0;
            border: none;
            outline: none;
            vertical-align: top;
            image-rendering: -webkit-optimize-contrast;
            image-rendering: crisp-edges;
            /* 尺寸由 JavaScript 动态设置，保持图片比例 */
          }
          img.dragging {
            transition: none;
          }
          .zoom-indicator {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.6);
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
            pointer-events: none;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          }
          .zoom-indicator.show {
            opacity: 1;
          }
        </style>
      </head>
      <body>
        <div class="image-container">
          <img src="${objectUrl}" alt="${name}" id="previewImage" />
        </div>
        <div class="zoom-indicator" id="zoomIndicator">100%</div>
        <script>
          class ImageZoom {
            constructor() {
              this.img = document.getElementById('previewImage');
              this.zoomIndicator = document.getElementById('zoomIndicator');
              this.scale = 1;
              this.minScale = 0.5;
              this.maxScale = 5;
              this.isDragging = false;
              this.dragStart = { x: 0, y: 0 };
              this.translateX = 0;
              this.translateY = 0;
              this.zoomTimeout = null;
              
              this.init();
            }
            
            init() {
              // 图片加载完成后调整窗口大小
              this.img.onload = () => {
                this.resizeWindowToImage();
              };
              
              // 阻止图片的默认拖拽行为
              this.img.addEventListener('dragstart', (e) => e.preventDefault());
              this.img.addEventListener('contextmenu', (e) => e.preventDefault());
              
              // 滚轮缩放
              this.img.addEventListener('wheel', this.handleWheel.bind(this));
              
              // 拖拽移动
              this.img.addEventListener('mousedown', this.startDrag.bind(this));
              document.addEventListener('mousemove', this.drag.bind(this));
              document.addEventListener('mouseup', this.endDrag.bind(this));
              
              // 双击重置
              this.img.addEventListener('dblclick', this.reset.bind(this));
              
              // ESC 键关闭
              document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                  window.close();
                }
              });
              
              // 清理资源
              setTimeout(() => URL.revokeObjectURL('${objectUrl}'), 10000);
            }
            
            resizeWindowToImage() {
              // 获取图片的原始像素尺寸
              const imageWidth = this.img.naturalWidth;
              const imageHeight = this.img.naturalHeight;
              
              // 计算窗口边框和标题栏的尺寸
              const titleBarHeight = window.outerHeight - window.innerHeight;
              const sideBorderWidth = window.outerWidth - window.innerWidth;
              
              // 固定窗口高度（内容区域）
              const fixedContentHeight = 600; // 固定高度600px
              
              // 根据图片比例计算宽度
              const imageRatio = imageWidth / imageHeight;
              const calculatedContentWidth = fixedContentHeight * imageRatio;
              
              // 窗口总尺寸 = 内容尺寸 + 系统边框
              const windowWidth = calculatedContentWidth + sideBorderWidth;
              const windowHeight = fixedContentHeight + titleBarHeight;
              
              // 限制最小和最大窗口大小
              const minWidth = 200;
              const minHeight = 200;
              const maxWidth = window.screen.width * 0.95;
              const maxHeight = window.screen.height * 0.95;
              
              const finalWidth = Math.max(minWidth, Math.min(maxWidth, windowWidth));
              const finalHeight = Math.max(minHeight, Math.min(maxHeight, windowHeight));
              
              // 调整窗口大小
              window.resizeTo(finalWidth, finalHeight);
              
              // 居中显示窗口
              const left = Math.max(0, (window.screen.width - finalWidth) / 2);
              const top = Math.max(0, (window.screen.height - finalHeight) / 2);
              window.moveTo(left, top);
              
              // 设置图片尺寸以保持比例，确保像素完美对齐
              this.img.style.width = Math.round(calculatedContentWidth) + 'px';
              this.img.style.height = Math.round(fixedContentHeight) + 'px';
              this.img.style.imageRendering = 'crisp-edges';
              
              // 更新窗口标题，显示图片像素尺寸
              this.updateWindowTitle(imageWidth, imageHeight);
            }
            
            updateWindowTitle(width, height) {
              const originalTitle = document.title;
              const pixelInfo = \` (\${width} × \${height})\`;
              
              // 如果标题还没有像素信息，则添加
              if (!originalTitle.includes(' × ')) {
                document.title = originalTitle + pixelInfo;
              }
            }
            
            handleWheel(e) {
              e.preventDefault();
              
              const rect = this.img.getBoundingClientRect();
              const mouseX = e.clientX - rect.left;
              const mouseY = e.clientY - rect.top;
              
              // 计算鼠标在图片中的相对位置
              const relativeX = (mouseX - rect.width / 2) / this.scale;
              const relativeY = (mouseY - rect.height / 2) / this.scale;
              
              // 缩放
              const delta = e.deltaY > 0 ? 0.9 : 1.1;
              const newScale = Math.max(this.minScale, Math.min(this.maxScale, this.scale * delta));
              
              if (newScale !== this.scale) {
                // 计算新的平移量，使缩放以鼠标位置为中心
                const scaleDiff = newScale - this.scale;
                this.translateX -= relativeX * scaleDiff;
                this.translateY -= relativeY * scaleDiff;
                
                this.scale = newScale;
                this.updateTransform();
                this.showZoomIndicator();
              }
            }
            
            startDrag(e) {
              // 允许在任何缩放级别下拖拽
              e.preventDefault(); // 阻止默认行为
              this.isDragging = true;
              this.dragStart = { x: e.clientX, y: e.clientY };
              this.img.style.cursor = 'grabbing';
              this.img.classList.add('dragging'); // 添加拖拽类，禁用过渡效果
            }
            
            drag(e) {
              if (!this.isDragging) return;
              e.preventDefault();
              
              const deltaX = e.clientX - this.dragStart.x;
              const deltaY = e.clientY - this.dragStart.y;
              
              // 直接使用鼠标移动距离，不除以缩放比例
              this.translateX += deltaX;
              this.translateY += deltaY;
              
              this.dragStart = { x: e.clientX, y: e.clientY };
              this.updateTransform();
            }
            
            endDrag() {
              this.isDragging = false;
              this.img.style.cursor = 'pointer'; // 统一使用 pointer 光标
              this.img.classList.remove('dragging'); // 移除拖拽类，恢复过渡效果
            }
            
            reset() {
              this.scale = 1;
              this.translateX = 0;
              this.translateY = 0;
              this.updateTransform();
              this.showZoomIndicator();
            }
            
            updateTransform() {
              // 将平移量除以缩放比例，确保拖拽时图片完全跟随鼠标
              const adjustedTranslateX = this.translateX / this.scale;
              const adjustedTranslateY = this.translateY / this.scale;
              const transform = \`scale(\${this.scale}) translate(\${adjustedTranslateX}px, \${adjustedTranslateY}px)\`;
              this.img.style.transform = transform;
              // 光标状态由 startDrag/endDrag 方法控制
            }
            
            showZoomIndicator() {
              // 显示缩放倍数
              const zoomPercent = Math.round(this.scale * 100);
              this.zoomIndicator.textContent = \`\${zoomPercent}%\`;
              this.zoomIndicator.classList.add('show');
              
              // 清除之前的定时器
              if (this.zoomTimeout) {
                clearTimeout(this.zoomTimeout);
              }
              
              // 2秒后隐藏指示器
              this.zoomTimeout = setTimeout(() => {
                this.zoomIndicator.classList.remove('show');
              }, 2000);
            }
          }
          
          // 初始化图片缩放功能
          new ImageZoom();
        </script>
      </body>
      </html>
    `;
  } else if (name.endsWith('.txt')) {
    content = `
      <!DOCTYPE html>
      <html>
      <head>
        ${baseHead(file.name)}
        <style>
          iframe {
            width: 100vw; 
            height: 100vh; 
            border: none;
            background: #ffffff;
          }
        </style>
      </head>
      <body>
        <iframe src="${objectUrl}"></iframe>
      </body>
      </html>
    `;
  } else if (name.endsWith('.docx')) {
    content = `
      <!DOCTYPE html>
      <html>
      <head>
        ${baseHead(file.name)}
        <style>
          #docx-container {
            position: fixed; 
            inset: 0; 
            overflow: auto;
            padding: 20px;
            background: #ffffff;
          }
          .loading {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-size: 16px;
            color: #6b7280;
          }
        </style>
      </head>
      <body>
        <div id="docx-container">
          <div class="loading">正在加载 DOCX 预览...</div>
        </div>
        <script>
          // 使用 mammoth.js 库进行 DOCX 预览
          const container = document.getElementById('docx-container');
          const fileUrl = "${objectUrl}";
          
          // 显示加载状态
          container.innerHTML = \`
            <div id="docx-content" style="font-family: 'Times New Roman', 'Calibri', 'Arial', sans-serif; line-height: 1.6; color: #333; padding: 20px; background: #fff;">
              正在加载 mammoth.js 库...
            </div>
          \`;
          
          // 加载 mammoth.js 库
          const script = document.createElement('script');
          script.src = 'https://unpkg.com/mammoth@1.6.0/mammoth.browser.min.js';
          
          script.onload = function() {
            console.log('mammoth.js 加载成功');
            const contentDiv = document.getElementById('docx-content');
            if (contentDiv) {
              contentDiv.textContent = '正在解析 DOCX 文档...';
            }
            
            // 开始解析文档
            fetch(fileUrl)
              .then(response => {
                if (!response.ok) throw new Error('文件加载失败');
                return response.arrayBuffer();
              })
              .then(arrayBuffer => {
                if (window.mammoth && window.mammoth.convertToHtml) {
                  return window.mammoth.convertToHtml({arrayBuffer: arrayBuffer});
                } else {
                  throw new Error('mammoth.js 库未正确加载');
                }
              })
              .then(result => {
                const contentDiv = document.getElementById('docx-content');
                if (contentDiv) {
                  contentDiv.innerHTML = result.value;
                  
                  // 添加样式优化
                  const style = document.createElement('style');
                  style.textContent = \`
                    #docx-content {
                      font-family: 'Times New Roman', 'Calibri', 'Arial', sans-serif;
                      line-height: 1.6;
                      color: #333;
                      width: 100%;
                      max-width: 100%;
                      box-sizing: border-box;
                      overflow-x: auto;
                      overflow-y: auto;
                      word-wrap: break-word;
                      word-break: break-word;
                      margin: 0;
                      padding: 20px;
                      background: #fff;
                    }
                    #docx-content * {
                      max-width: 100%;
                      box-sizing: border-box;
                    }
                    #docx-content p { 
                      margin: 0 0 12px 0; 
                      text-align: justify;
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                    }
                    #docx-content h1, #docx-content h2, #docx-content h3,
                    #docx-content h4, #docx-content h5, #docx-content h6 { 
                      margin: 20px 0 12px 0; 
                      font-weight: 600; 
                      color: #1a1a1a;
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                    }
                    #docx-content h1 { font-size: 24px; }
                    #docx-content h2 { font-size: 20px; }
                    #docx-content h3 { font-size: 18px; }
                    #docx-content table { 
                      border-collapse: collapse; 
                      width: 100%; 
                      max-width: 100%;
                      margin: 16px 0;
                      table-layout: fixed;
                      word-wrap: break-word;
                    }
                    #docx-content table, #docx-content th, #docx-content td { 
                      border: 1px solid #ddd; 
                    }
                    #docx-content th, #docx-content td { 
                      padding: 8px 12px; 
                      text-align: left; 
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                      max-width: 200px;
                    }
                    #docx-content th { 
                      background-color: #f5f5f5; 
                      font-weight: 600; 
                    }
                    #docx-content ul, #docx-content ol { 
                      margin: 12px 0; 
                      padding-left: 24px; 
                      word-wrap: break-word;
                    }
                    #docx-content li { 
                      margin: 4px 0; 
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                    }
                    #docx-content blockquote { 
                      margin: 16px 0; 
                      padding: 12px 16px; 
                      background: #f8f9fa; 
                      border-left: 4px solid #007bff; 
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                    }
                    #docx-content img {
                      max-width: 100%;
                      height: auto;
                    }
                    #docx-content pre {
                      white-space: pre-wrap;
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                      max-width: 100%;
                    }
                    #docx-content code {
                      word-wrap: break-word;
                      overflow-wrap: break-word;
                    }
                  \`;
                  document.head.appendChild(style);
                  
                  // 不显示警告信息，只显示纯文档内容
                }
              })
              .catch(error => {
                console.error('DOCX 预览错误:', error);
                const contentDiv = document.getElementById('docx-content');
                if (contentDiv) {
                  contentDiv.innerHTML = \`
                    <div style="color: #e74c3c; padding: 20px; background: #fdf2f2; border: 1px solid #fecaca; border-radius: 4px;">
                      <h3 style="margin: 0 0 10px 0;">预览失败</h3>
                      <p style="margin: 0; font-size: 14px;">错误: \${error.message}</p>
                      <p style="margin: 10px 0 0 0; font-size: 12px; color: #666;">建议：尝试将文件转换为 PDF 格式</p>
                    </div>
                  \`;
                }
              });
          };
          
          script.onerror = function() {
            console.error('mammoth.js 加载失败');
            const contentDiv = document.getElementById('docx-content');
            if (contentDiv) {
              contentDiv.innerHTML = \`
                <div style="color: #e74c3c; padding: 20px; background: #fdf2f2; border: 1px solid #fecaca; border-radius: 4px;">
                  <h3 style="margin: 0 0 10px 0;">库加载失败</h3>
                  <p style="margin: 0; font-size: 14px;">无法加载 mammoth.js 库</p>
                  <p style="margin: 10px 0 0 0; font-size: 12px; color: #666;">请检查网络连接</p>
                </div>
              \`;
            }
          };
          
          document.head.appendChild(script);
        </script>
      </body>
      </html>
    `;
  } else if (name.endsWith('.doc')) {
    content = `
      <!DOCTYPE html>
      <html>
      <head>
        ${baseHead(file.name)}
      </head>
      <body>
        <div class="preview-error">
          <h2>暂不支持 .doc 预览</h2>
          <p>.doc 是旧版 Microsoft Word 格式，无法在线预览</p>
          <p>建议：将文件另存为 .docx 格式或下载后使用 Microsoft Word 打开</p>
          <div style="margin-top: 20px;">
            <a href="${objectUrl}" download="${file.name}" class="preview-btn preview-btn--primary">下载文件</a>
          </div>
        </div>
      </body>
      </html>
    `;
  } else {
    content = `
      <!DOCTYPE html>
      <html>
      <head>
        ${baseHead(file.name)}
      </head>
      <body>
        <div class="preview-error">
          <h2>暂不支持该文件类型的在线预览</h2>
          <p>文件类型: <span class="file-type">${name.split('.').pop()}</span></p>
          <a href="${objectUrl}" download="${file.name}" class="preview-btn preview-btn--primary">下载文件</a>
        </div>
      </body>
      </html>
    `;
  }

  // 浏览器打开，Electron 主进程将拦截并转换为模态子窗口
  const win = window.open('', '_blank', 'width=1200,height=800,scrollbars=no,resizable=yes,toolbar=no,menubar=no,location=no,status=no');
  if (win) {
    win.document.write(content);
    win.document.close();
  }

  // 延迟释放以保证子窗口可访问
  setTimeout(() => URL.revokeObjectURL(objectUrl), 10000);
}

export default openFilePreviewWindow;


